package com.ftg.learn.service.impl;

import com.ftg.learn.dto.UserDto;
import com.ftg.learn.entity.UserEntitiy;
import com.ftg.learn.mapper.UserMapper;
import com.ftg.learn.service.UserService;
import com.ftg.learn.util.R;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author 布衣
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    UserMapper userMapper;

    @Override
    public R<String> login(UserDto userDto) {
        if(userDto.getUsername().isEmpty()){
            return R.failure("用户名不能为空!!!");
        }

        if(userDto.getPassword().isEmpty()){
            return R.failure("密码不能为空!!!");
        }
        UserEntitiy byUsername = userMapper.findByUsername(userDto.getUsername());
        if(byUsername == null){
            return R.failure("用户名不存在!!!");
        }

        System.out.println(byUsername.getPassword()+"byUsername.getPassword()");
        System.out.println(userDto.getPassword()+"userDto.getPassword()");
        if (!byUsername.getPassword().equals(userDto.getPassword())) {
            return R.ok("密码错误，请重新输入");
        }
        String token = Jwts.builder()
                .claim("username", byUsername.getUsername())
                .claim("id", byUsername.getId())
                .signWith(SignatureAlgorithm.HS256, "secret")
                .compact();

        return R.ok(token);
    }

    public static void main(String[] args) {
        //jwts加密
        System.out.println(Jwts.builder()
                .setSubject("user")
                .claim("username", "admin")
                .claim("password", "123456")
                .signWith(SignatureAlgorithm.HS256, "secret")
                .compact());
        //解析token

        Object o = Jwts.parser().setSigningKey("secret").parse("eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyIiwidXNlcm5hbWUiOiJhZG1pbiIsInBhc3N3b3JkIjoiMTIzNDU2In0.8yLeKrMJYeLaco2ZSPQNaQCHqV0VLridkIUVJXMy5oQ");
        System.out.println(o);
    }
}
